package match

import (
	"sanguo/node/node_team"
	"sanguo/node/node_team/com"
	"sanguo/node/node_team/team"
	"time"

	"github.com/sniperHW/kendynet/event"
)

var MatchMgr MatchManager

type MatchManager struct {
	RoleToObj    map[uint64]*Object
	RoleToRoom   map[uint64]*Room
	RoomMap      map[int64]*Room
	BLQueues     map[int32]*BattleLevelQueue
	processQueue *event.EventQueue
}

type BattleLevelQueue struct {
	BattleLevelType int32
	MatchQueue      map[int32]*Queue
	eventQueue      *event.EventQueue
}

func (this *MatchManager) PostTask(task func()) {
	this.processQueue.Post(task)
}

func (this *BattleLevelQueue) PostTask(task func()) {
	this.eventQueue.Post(task)
}

func (this *MatchManager) GetMatchQueue(battleLevelType, level int32) *Queue {
	blQueue := this.BLQueues[battleLevelType]
	if blQueue != nil {
		return blQueue.MatchQueue[level]
	}
	return nil
}

func (this *MatchManager) tick(now time.Time) {
	//房间超时处理
	for _, room := range this.RoomMap {
		if now.Unix() > room.DestroyTime {
			node_team.Infoln("Room TimeOut, Delete RoomID:", room.RoomID)
			for _, r := range room.Roles {
				delete(this.RoleToRoom, r.RoleID)
			}
			delete(this.RoomMap, room.RoomID)

			_team := team.TeamMgr.GetTeam(room.TeamID)
			if _team != nil {
				_team.Status = com.TeamStatus_Safe
			}
		}
	}

}

func (this *MatchManager) InitBattleLevelQueue() bool {
	for i := int32(1); i <= 3; i++ {
		blQueue := &BattleLevelQueue{
			BattleLevelType: i,
			MatchQueue:      map[int32]*Queue{},
			eventQueue:      event.NewEventQueue(),
		}
		for j := int32(10); j <= 10; /*GlobalConstData.RoleMaxLevel; */ j += 10 {
			blQueue.MatchQueue[j] = NewQueue(i, j)
		}

		this.BLQueues[i] = blQueue

		go func() {
			blQueue.eventQueue.Run()
		}()

		go func() {
			for {
				time.Sleep(time.Millisecond * 500)
				now := time.Now()
				for _, queue := range blQueue.MatchQueue {
					blQueue.PostTask(func() {
						queue.TryMatch(now)
					})
				}

			}
		}()

	}
	return true
}

func Init() bool {
	MatchMgr = MatchManager{
		RoleToObj:    map[uint64]*Object{},
		RoleToRoom:   map[uint64]*Room{},
		RoomMap:      map[int64]*Room{},
		BLQueues:     map[int32]*BattleLevelQueue{},
		processQueue: event.NewEventQueue(),
	}

	go func() {
		MatchMgr.processQueue.Run()
	}()

	go func() {
		for {
			now := time.Now()
			time.Sleep(time.Millisecond * 500)
			MatchMgr.PostTask(func() { MatchMgr.tick(now) })
		}
	}()

	return MatchMgr.InitBattleLevelQueue()
}
